import logging
import yaml
import time

from PyQt5.QtWidgets import QMessageBox

import configs.strings as strs

ERROR = -1
INFO = 1
WARNING = 2
DEFAULT = 3

CONFIG_FILE = 'configs/appconfig.yml'


def basic_log_config(debug=True):
    """
    日志输出格式设定
    :param debug: 是否为DEBUG模式
    :return:
    """
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
    if debug:
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
    else:
        logFilename = './logs/' + time.strftime("%Y_%m_%d", time.localtime()) + '.log'
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT, filename=logFilename,
                            filemode='a')


def load_yaml(filepath=CONFIG_FILE):
    """
    加载yaml配置文件
    :param filepath: 文件路径
    :return:
    """
    try:
        with open(filepath, 'r') as f:
            data = yaml.load(f, Loader=yaml.SafeLoader)
            return data
    except Exception as e:
        return ERROR, e


def generate_yaml_doc(yaml_file, yaml_obj):
    """
    生成yaml配置文件
    :param yaml_file: 文件路径
    :param yaml_obj: 保存内容，必须为字典格式
    :return:
    """
    if type(yaml_obj).__name__ == 'dict':
        try:
            file = open(yaml_file, 'w', encoding='utf-8')
            yaml.dump(yaml_obj, file)
            file.close()
            return file.name
        except Exception as e:
            return errorhandle.SAVE_YAML_EXCEPTION
    else:
        return errorhandle.SAVE_YAML_DATA_FORMAT_EXCEPTION


def message_box(title, msg):
    """
    # 桌面弹出消息框
    # Python弹出Windows自带的MessageBox
    :param title:
    :param msg:
    :return:
    """
    import ctypes
    ctypes.windll.user32.MessageBoxW(0, msg, title, 1)


def show_dialog(frame, msg, msg_type):
    """
    根据消息类型显示对话框以及提示信息
    :param frame: 对话框框架
    :param msg: 需要显示的信息
    :param msg_type: 信息类型: INFO, WARNING, ERROR
    :return:
    """
    res = -1
    if msg_type == INFO:
        res = QMessageBox.information(frame, "INFO", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
    elif msg_type == WARNING:
        res = QMessageBox.warning(frame, "WARNING", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
    elif msg_type == ERROR:
        res = QMessageBox.critical(frame, "ERROR", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
    if res == QMessageBox.Yes:
        return 0
    else:
        return -1


def make_font(font=DEFAULT, msg=''):
    """
    To set font of text show in text browser
    :param font: DEFAULT, INFO, ERROR, WARNING
    :param msg: message to show
    :return: matched font
    """
    if font == ERROR:
        return '<font size={} color="{}" face="{}"> {} </font>'.format(6, "red", "verdana", msg)
    if font == INFO:
        return '<font size={} color="{}" face="{}"> {} </font>'.format(5, "green", "verdana", msg)
    if font == WARNING:
        return '<font size={} color="{}" face="{}"> {} </font>'.format(5, "grey", "verdana", msg)
    else:
        return '<font size={} color="{}" face="{}"> {} </font>'.format(5, "black", "verdana", msg)


def parse_para_range(rangeStr, lang):
    """
    根据当前语言和用户选择的量程判断是大量程还是小量程
    :param rangeStr: 选择结果
    :param lang: 当前所用语言
    :return: 1： 小量程     2： 大量程
    """
    if rangeStr == strs.translate['S_RANGE'][lang]:
        return 1  # 小量程
    if rangeStr == strs.translate['B_RANGE'][lang]:
        return 2  # 大量程


def save_data_pickle(data, filepath='', instType='radar', filetype='pickle', filename=''):
    """
    将数据以 时间-类别.后缀 的命名方式保存为用户指定的文件类型
    :param filename: 既定的文件名， 如果filename为缺省值， 则自动根据时间文件格式选择文件名
    :param data: 要保存的数据
    :param filepath: 保存路径，如果保存路径未写，则默认路径为./data
    :param instType: 来自instType的数据比如GPS， 雷达， 无人机等
    :param filetype: 可供选择的有pickle，csv, txt
    :return: 保存成功返回文件名，失败返回-1
    """
    if filename == '':
        filename = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '_' + instType
    if filetype == 'pickle':
        import pickle
        filename = filename + '.pkl'
    if filetype == 'csv':
        import pandas as pd
        filename = filename + '.csv'
    if filetype == 'txt':
        filename = filename + '.txt'

    if not filepath:
        filepath = "./data"
    filepath = filepath + '/' + filename

    try:
        if filetype == 'pickle':
            f = open(filepath, 'wb')
            pickle.dump(data, f)
            f.close()
            return f.name
        if filetype == 'csv':
            save = pd.DataFrame(data)
            save.to_csv(filepath, index=False, header=False)
            return filepath
        if filetype == 'txt':
            if isinstance(data, str):
                f = open(filepath, 'w')
                f.write(data)
                f.close()
            if isinstance(data, list) or isinstance(data, dict):
                f = open(filepath, 'w')
                for line in data:
                    f.write(str(line) + '\n')
                f.close()
    except Exception as e:
        return errorhandle.SAVE_PICKLE_ERROR
